# Copyright (c) 2012, Bin Tan
# This file is distributed under the BSD Licence. See python-epub-builder-license.txt for details.

import os
from epubbuilder import epub

class Section:

    def __init__(self):
        self.title = ''
        self.subsections = []
        self.css = ''
        self.text = []
        self.templateFileName = 'ez-section.html'

        
class Book:
    
    def __init__(self,templates=None):
        self.impl = epub.EpubBook(templates)
        self.title = ''
        self.authors = []
        self.cover = ''
        self.lang = 'en-US'
        self.sections = []
        self.environment=self.impl.environment
       
    def __addSection(self, section, id, depth):
        if depth > 0:
            tmpl = self.environment.get_template(section.templateFileName)
            html = tmpl.render(section = section)
            item = self.impl.addHtml('', '%s.html' % id, html)
            self.impl.addSpineItem(item)
            self.impl.addTocMapNode(item.destPath, section.title, depth)
            id += '.'
        if len(section.subsections) > 0:
            for i, subsection in enumerate(section.subsections):
                self.__addSection(subsection, id + str(i + 1), depth + 1)
    
    """
    create epub book.
    mode, "epub" to create singal epub file, "opf" to create dir & opf file
    """
    def make(self, outputDir, mode="epub"):
        outputFile = outputDir + '.epub'
        
        self.impl.setTitle(self.title)
        self.impl.setLang(self.lang)
        for author in self.authors:
            self.impl.addCreator(author)
        if self.cover:
            self.impl.addCover(self.cover)
        self.impl.addTitlePage()
        self.impl.addTocPage()
        root = Section()
        root.subsections = self.sections
        self.__addSection(root, 's', 0)
        self.impl.createBook(outputDir)
        if mode=="epub" or mode is None:
            self.impl.createArchive(outputDir, outputFile)
        #self.impl.checkEpub('epubcheck-1.0.5.jar', outputFile)
